<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <div class="left-section">
            <el-button icon="ArrowLeft" @click="goBack">返回车辆列表</el-button>
            <span class="title">车辆图片管理</span>
          </div>
          <div class="right-section">
            <el-button type="primary" icon="Plus" @click="handleUpload">上传图片</el-button>
            <el-button type="success" icon="FolderAdd" @click="showFolderUploadDialog">文件夹上传</el-button>
          </div>
        </div>
      </template>

      <el-upload
        v-model:file-list="fileList"
        :action="uploadUrl"
        :headers="headers"
        :data="uploadData"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleUploadSuccess"
        :before-upload="beforeUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <div class="photo-actions" v-if="fileList.length > 0">
        <el-button type="primary" @click="handleSetMainPhoto" :disabled="!selectedPhoto">设为封面</el-button>
        <el-button @click="handleMoveUp" :disabled="!selectedPhoto || selectedPhotoIndex === 0">上移</el-button>
        <el-button @click="handleMoveDown" :disabled="!selectedPhoto || selectedPhotoIndex === fileList.length - 1">下移</el-button>
      </div>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <!-- 文件夹上传对话框 -->
      <el-dialog
        v-model="folderUploadDialogVisible"
        title="文件夹上传"
        width="500px"
      >
        <div class="folder-upload-content">
          <p>请选择要上传的图片文件，可多选（最多50张）</p>
          <el-upload
            ref="folderUploadRef"
            action="#"
            :auto-upload="false"
            multiple
            :limit="50"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            accept="image/*"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                仅支持jpg/png等图片文件，且不超过5MB
              </div>
            </template>
          </el-upload>
          <div class="upload-status" v-if="uploadingFiles">
            <p>正在上传: {{ uploadProgress }}/{{ totalFiles }}</p>
            <el-progress :percentage="uploadPercentage"></el-progress>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-checkbox v-model="setFirstAsMain">将第一张图片设为主图</el-checkbox>
            <el-button @click="folderUploadDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitFolderUpload" :loading="uploadingFiles">
              开始上传
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ArrowLeft, FolderAdd } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const carId = route.params.id

const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const selectedPhoto = ref(null)
const uploadUrl = 'http://localhost:9999/api/car-photos/upload'
const headers = {
  Authorization: 'Bearer ' + getToken()
}
const uploadData = {
  carId: carId,
  isMain: false
}

// 文件夹上传相关变量
const folderUploadDialogVisible = ref(false)
const folderUploadRef = ref(null)
const selectedFiles = ref([])
const uploadingFiles = ref(false)
const uploadProgress = ref(0)
const totalFiles = ref(0)
const uploadPercentage = ref(0)
const setFirstAsMain = ref(false)

// 计算选中的照片索引
const selectedPhotoIndex = computed(() => {
  if (!selectedPhoto.value) return -1
  return fileList.value.findIndex(item => item.uid === selectedPhoto.value.uid)
})

// 获取车辆图片列表
const getPhotoList = async () => {
  try {
    console.log('Fetching photos for car ID:', carId);
    const response = await request({
      url: `/api/car-photos/car/${carId}`,
      method: 'get'
    });
    
    console.log('Received photo data:', response);
    
    // 处理返回的数据格式
    if (Array.isArray(response)) {
      fileList.value = response.map(photo => ({
        name: photo.photoUrl.split('/').pop() || 'car-photo',
        url: photo.photoUrl, // 直接使用photoUrl，不添加前缀
        isMain: photo.isMain,
        photoId: photo.photoId,
        uid: photo.photoId.toString() // 使用photoId作为uid
      }));
    } else if (response && typeof response === 'object') {
      // 如果返回的是单个对象，转换为数组
      fileList.value = [{
        name: response.photoUrl.split('/').pop() || 'car-photo',
        url: response.photoUrl, // 直接使用photoUrl，不添加前缀
        isMain: response.isMain,
        photoId: response.photoId,
        uid: response.photoId.toString()
      }];
    } else {
      fileList.value = [];
      console.error('Unexpected data format:', response);
    }
    
    // 默认选中第一张图片
    if (fileList.value.length > 0) {
      selectedPhoto.value = fileList.value[0];
    }
    
    console.log('Processed file list:', fileList.value);
  } catch (error) {
    console.error('获取图片列表失败:', error);
    ElMessage.error('获取图片列表失败: ' + (error.message || '未知错误'));
    fileList.value = [];
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  console.log('Upload success response:', response);
  
  // 检查响应格式
  if (response && response.photoId) {
    // 直接使用响应中的photoId
    file.photoId = response.photoId;
    file.uid = response.photoId.toString();
  } else if (response && response.data && response.data.photoId) {
    // 如果响应格式是 {data: {photoId: ...}}
    file.photoId = response.data.photoId;
    file.uid = response.data.photoId.toString();
  }
  
  ElMessage.success('上传成功');
  getPhotoList();
}

// 删除图片
const handleRemove = async (file) => {
  try {
    const photoId = file.photoId || file.response?.photoId;
    if (!photoId) {
      ElMessage.error('无法获取图片ID，删除失败');
      return;
    }
    
    console.log('Deleting photo with ID:', photoId);
    await request({
      url: `/api/car-photos/${photoId}`,
      method: 'delete'
    });
    
    ElMessage.success('删除成功');
    getPhotoList();
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败: ' + (error.message || '未知错误'));
  }
}

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
  selectedPhoto.value = file
}

// 上传图片
const handleUpload = () => {
  // 触发上传组件的点击事件
  document.querySelector('.el-upload--picture-card').click()
}

// 设置主图
const handleSetMainPhoto = async () => {
  if (!selectedPhoto.value) {
    ElMessage.warning('请先选择一张图片');
    return;
  }

  try {
    console.log('Setting main photo:', selectedPhoto.value);
    await request({
      url: `/api/car-photos/${selectedPhoto.value.photoId}/main`,
      method: 'put',
      params: { carId: carId }
    });

    ElMessage.success('设置主图成功');
    getPhotoList();
  } catch (error) {
    console.error('设置主图失败:', error);
    ElMessage.error('设置主图失败: ' + (error.message || '未知错误'));
  }
}

// 上移图片
const handleMoveUp = async () => {
  if (!selectedPhoto.value || selectedPhotoIndex.value <= 0) return
  
  const currentIndex = selectedPhotoIndex.value
  const targetIndex = currentIndex - 1
  
  try {
    const photoId = selectedPhoto.value.photoId
    await request({
      url: `/api/car-photos/${photoId}/sort`,
      method: 'put',
      params: { sortOrder: targetIndex }
    });
    
    // 更新目标图片的排序
    const targetPhotoId = fileList.value[targetIndex].photoId
    await request({
      url: `/api/car-photos/${targetPhotoId}/sort`,
      method: 'put',
      params: { sortOrder: currentIndex }
    });
    
    ElMessage.success('排序更新成功')
    getPhotoList()
  } catch (error) {
    console.error('排序更新失败:', error);
    ElMessage.error('排序更新失败: ' + (error.message || '未知错误'));
  }
}

// 下移图片
const handleMoveDown = async () => {
  if (!selectedPhoto.value || selectedPhotoIndex.value >= fileList.value.length - 1) return
  
  const currentIndex = selectedPhotoIndex.value
  const targetIndex = currentIndex + 1
  
  try {
    const photoId = selectedPhoto.value.photoId
    await request({
      url: `/api/car-photos/${photoId}/sort`,
      method: 'put',
      params: { sortOrder: targetIndex }
    });
    
    // 更新目标图片的排序
    const targetPhotoId = fileList.value[targetIndex].photoId
    await request({
      url: `/api/car-photos/${targetPhotoId}/sort`,
      method: 'put',
      params: { sortOrder: currentIndex }
    });
    
    ElMessage.success('排序更新成功')
    getPhotoList()
  } catch (error) {
    console.error('排序更新失败:', error);
    ElMessage.error('排序更新失败: ' + (error.message || '未知错误'));
  }
}

// 显示文件夹上传对话框
const showFolderUploadDialog = () => {
  folderUploadDialogVisible.value = true;
  selectedFiles.value = [];
  uploadProgress.value = 0;
  totalFiles.value = 0;
  uploadPercentage.value = 0;
}

// 处理选择的文件变化
const handleFileChange = (file, fileList) => {
  selectedFiles.value = fileList;
}

// 处理超出文件数限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传50张图片');
}

// 提交文件夹上传
const submitFolderUpload = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请先选择要上传的图片');
    return;
  }

  uploadingFiles.value = true;
  uploadProgress.value = 0;
  totalFiles.value = selectedFiles.value.length;
  
  try {
    // 准备表单数据
    const formData = new FormData();
    formData.append('carId', carId);
    formData.append('isMain', setFirstAsMain.value);
    
    // 添加所有文件
    selectedFiles.value.forEach(file => {
      formData.append('files', file.raw);
    });
    
    // 发送请求
    const response = await fetch('http://localhost:9999/api/car-photos/batch-upload', {
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      body: formData
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    console.log('Batch upload result:', result);
    
    ElMessage.success(`成功上传 ${result.length} 张图片`);
    folderUploadDialogVisible.value = false;
    
    // 刷新图片列表
    getPhotoList();
  } catch (error) {
    console.error('批量上传失败:', error);
    ElMessage.error('批量上传失败: ' + (error.message || '未知错误'));
  } finally {
    uploadingFiles.value = false;
    if (folderUploadRef.value) {
      folderUploadRef.value.clearFiles();
    }
  }
}

// 返回车辆列表
const goBack = () => {
  router.push('/admin/car/list')
}

onMounted(() => {
  getPhotoList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.right-section {
  display: flex;
  gap: 10px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.photo-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.folder-upload-content {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.upload-status {
  margin-top: 15px;
}
</style> 